package com.itheima.controller;

import com.itheima.pojo.Category;
import com.itheima.pojo.Result;
import com.itheima.service.CategoryService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    /*  新增文章分类 */
    @PostMapping
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }

    /*  获取该用户下的所有文章列表  */
    @GetMapping
    public Result<List<Category>> list() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer id = (Integer) claims.get("id");
        List<Category> list = categoryService.list(id);
        return Result.success(list);
    }

    /* 获取指定某条文章信息 */
    @GetMapping("/detail")
    public Result<Category> findById(@RequestParam Integer id) {
        Category category = categoryService.findById(id);
        return Result.success(category);
    }

    /*  更新文章列表  */
    @PutMapping
    public Result update(@RequestBody @Validated(Category.Update.class) Category category) {
        categoryService.update(category);
        return Result.success();
    }

    /*  删除文章列表  */
    @DeleteMapping
    public Result delete(@RequestParam Integer id) {
        //因为只有只能删除自己新增的列表，因此得进行判断
        Category category = categoryService.findById(id);
        Integer createUser = category.getCreateUser();
        Map<String, Object> claims = ThreadLocalUtil.get();
        Integer userId = (Integer) claims.get("id");
        if(!createUser.equals(userId)) {
            return Result.error("没有该操作权限！！！");
        }
        //当两个用户信息相同的时候可以进行删除
        categoryService.delete(id);
        return Result.success();
    }
}
